﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Xml;
using Up6.core.Configs;

namespace Up6.core.EF;

public class EFContext : DbContext
{
    private IOptions<AppSetting> _appConfiguration;
    public EFContext(IOptions<AppSetting> appConfiguration)
    {
        _appConfiguration = appConfiguration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //optionsBuilder.EnableSensitiveDataLogging(true);  //允许打印参数
        InitDB(optionsBuilder);
        base.OnConfiguring(optionsBuilder);
    }

    //        protected override void OnModelCreating(ModelBuilder modelBuilder)
    //        {
    //            //modelBuilder.Entity<Users>()
    //            //    .HasKey(c => new { c.Id });



    //            foreach (var entity in modelBuilder.Model.GetEntityTypes())
    //            {
    //                modelBuilder.Entity(entity.Name, builder =>
    //                {
    //#if DEBUG
    //                    // builder.Property(entity.Name).HasComment

    //                    ////设置表的备注
    //                    //builder.ToTable(t => t.HasComment(GetEntityComment(entity.Name)));

    //                    builder.HasComment(GetEntityComment(entity.Name));

    //                    List<string> baseTypeNames = new();
    //                    var baseType = entity.ClrType.BaseType;
    //                    while (baseType != null)
    //                    {
    //                        baseTypeNames.Add(baseType.FullName!);
    //                        baseType = baseType.BaseType;
    //                    }
    //#endif

    //                    foreach (var property in entity.GetProperties())
    //                    {

    //#if DEBUG
    //                        //设置字段的备注
    //                        property.SetComment(GetEntityComment(entity.Name, property.Name, baseTypeNames));
    //#endif

    //                        //设置字段的默认值 
    //                        var defaultValueAttribute = property.PropertyInfo?.GetCustomAttribute<DefaultValueAttribute>();
    //                        if (defaultValueAttribute != null)
    //                        {
    //                            property.SetDefaultValue(defaultValueAttribute.Value);
    //                        }
    //                    }

    //                });
    //            }

    //        }

    #region 使用数据库类型
    /// <summary>
    /// 数据库
    /// </summary>
    /// <param name="optionsBuilder"></param>
    private void InitDB(DbContextOptionsBuilder optionsBuilder)
    {

        string connect = _appConfiguration.Value.ConnectionStrings["DemoDBContext"];

        optionsBuilder.UseSqlServer(connect);

    }
    #endregion

    #region 获取表&列注释
    public static string GetEntityComment(string typeName, string? fieldName = null, List<string>? baseTypeNames = null)
    {
        var path = Path.Combine(AppContext.BaseDirectory, "MinIO.Test.xml");
        XmlDocument xml = new();
        xml.Load(path);
        XmlNodeList memebers = xml.SelectNodes("/doc/members/member")!;

        Dictionary<string, string> fieldList = new();

        if (fieldName == null)
        {
            var matchKey = "T:" + typeName;

            foreach (object m in memebers)
            {
                if (m is XmlNode node)
                {
                    var name = node.Attributes!["name"]!.Value;

                    var summary = node.InnerText.Trim();

                    if (name == matchKey)
                    {
                        fieldList.Add(name, summary);
                    }
                }
            }

            return fieldList.FirstOrDefault(t => t.Key.ToLower() == matchKey.ToLower()).Value ?? typeName.ToString().Split(".").ToList().LastOrDefault()!;
        }
        else
        {

            foreach (object m in memebers)
            {
                if (m is XmlNode node)
                {
                    string name = node.Attributes!["name"]!.Value;

                    var summary = node.InnerText.Trim();

                    var matchKey = "P:" + typeName + ".";
                    if (name.StartsWith(matchKey))
                    {
                        name = name.Replace(matchKey, "");

                        fieldList.Remove(name);

                        fieldList.Add(name, summary);
                    }

                    if (baseTypeNames != null)
                    {
                        foreach (var baseTypeName in baseTypeNames)
                        {
                            if (baseTypeName != null)
                            {
                                matchKey = "P:" + baseTypeName + ".";
                                if (name.StartsWith(matchKey))
                                {
                                    name = name.Replace(matchKey, "");
                                    fieldList.Add(name, summary);
                                }
                            }
                        }
                    }
                }
            }

            return fieldList.FirstOrDefault(t => t.Key.ToLower() == fieldName.ToLower()).Value ?? fieldName;
        }
    }
    #endregion

    //public DbSet<System_FileUploadFolderInfo> SystemFileUploadFolderInfo { get; set; }
    //public DbSet<System_FileUploadInfo> SystemFileUploadInfoFile { get; set; }


}